package com.example.multinetty.netty.firstprotocal;

import com.example.multinetty.netty.send.ChannelSender;
import com.example.multinetty.netty.session.LocalSession;
import com.example.multinetty.netty.session.ServerSession;
import io.netty.channel.Channel;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ConcurrentHashMap;


@RestController
@RequestMapping(value = "/")
public class NettyUserController {
    private static final ConcurrentHashMap<Integer, ServerSession> onlineSessions = new ConcurrentHashMap<>();
    //此方法用于远程调用，需要加上Remote注解
    @RequestMapping(value="/getUserNameByIdext",method= RequestMethod.GET,produces = "text/html; charset=utf-8")
    public @ResponseBody String getUserNameById(String userId,HttpServletRequest request){
        //此处并未访问数据库，只是做简单输出
        //System.out.println("客户端请求的用户id为======" + request.getAttribute("channel"));
        System.out.println("客户端请求的用户id为======"+userId+request.getAttribute("channel"));
       LocalSession localSession=(LocalSession)request.getAttribute("channel");
        Channel channel=  localSession.getChannel();
//        channel.writeAndFlush("session back");
        onlineSessions.put(1,localSession);
        return "响应结果===用户张三"+userId;
    }
    //http://localhost:8033/sendback
    @RequestMapping(value = "/sendback",method = RequestMethod.GET)
    public void sendback(){
        String message="hello,welcome";
        System.out.println("message ："+message);
        Channel channel=( (LocalSession) onlineSessions.get(1)).getChannel();
        System.out.println("Channel ："+channel.toString());
        new ChannelSender(channel).sendback(message);

    }
}